package net.xi.news.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import net.xi.news.dao.VideoMapper;
import net.xi.news.pojo.News;
import net.xi.news.pojo.Video;
import net.xi.news.service.RedisService;
import net.xi.news.service.VideoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class VideoServiceImpl extends ServiceImpl<VideoMapper, Video> implements VideoService {

    @Autowired
    private VideoMapper videoMapper;

    @Autowired
    private RedisService redisService;

    /**
     * 查询视频列表
     * @param query
     * @param pageable
     * @return
     */
    @Override
    public Page<Video> listsearchVideo(String query, Pageable pageable){
        Page<Video> page=new Page<>();
        page.setCurrent(pageable.getPageNumber()+1);
        page.setSize(10);
        QueryWrapper<Video> queryWrapper=new QueryWrapper<>();
        if (!StringUtils.isEmpty(query)){
            queryWrapper.like("title",query);
        }
        queryWrapper.like("status",1);
        return videoMapper.selectPage(page,queryWrapper);
    }

    /**
     * 查询首页top5视频
     * @return
     */
    @Override
    public Page<Video> findVideoByPage(){
        String top5VIDEO = redisService.get("TOP5VIDEO");
        if (StringUtils.isEmpty(top5VIDEO)){
            LambdaQueryWrapper<Video> queryWrapper= Wrappers.lambdaQuery();
            queryWrapper.eq(Video::getStatus,1);
            queryWrapper.orderByAsc(Video::getCreateTime);
            Page<Video> page = this.page(new Page<Video>(1, 5), queryWrapper);
            String jsonlist = JSON.toJSONString(page.getRecords());
            System.out.println(jsonlist);
            redisService.set("TOP5VIDEO",60*60*24,jsonlist);
            return page;
        }else {
            List<Video> videos = JSON.parseArray(top5VIDEO, Video.class);
            System.out.println(videos);
            Page<Video> videoPage = new Page<>(1, 5);
            videoPage.setRecords(videos);
            return videoPage;
        }
    }
}
